import React, {useEffect, useState} from "react";
import {Dimensions, StyleSheet, Text, TouchableHighlight, View} from "react-native";
import {fontSize_12, fontSize_15, fontSize_16} from "./theme";
import {SvgXml} from "react-native-svg";
import {closeSvgXml} from "../libs/svgXml";
import SimpleToast from "react-native-simple-toast";
import {getWalletByMnemonic} from "./smartxL2Libs/smartxL2Web3";
import {addWallet, getWalletInfo, updateNowWallet, useWalletType, walletInfoType} from "./smartxL2Libs/L2_Data";

const {width,height,scale} = Dimensions.get("window");

const L2_CheckMnemonicView = ({navigation,route}:any) => {
    const [mnemonic,setMnemonic] = useState(route?.params?.mnemonic)
    const [randomMnemonic,setRandomMnemonic] = useState([" "," "," "," "," "," "," "," "," "," "," "," "])
    const [addMnemonic,setAddMnemonic] = useState([" "," "," "," "," "," "," "," "," "," "," "," "])
    const [addIndex,setAddIndex] = useState(0)
    const [canAddIndex,setCanAddIndex] = useState(true)
    const [walletInfo,setWalletInfo] = useState(route?.params?.walletInfo)
    const [chainID,setChainID] = useState(route?.params?.chainID)
    useEffect(()=>{
        console.log(mnemonic)
        navigation.setOptions({
            title:"验证助记词"
        })
        initRandomMnemonic()
    },[])
    //初始化随机单词位置
    const initRandomMnemonic = () => {
        let mnemonicTemp = [...mnemonic];
        let len = mnemonic.length;
        // console.log(`len:${len}`)
        for(let i = 0 ; i < len ;i++ )
        {
            let random = Math.floor(Math.random()*(len));
            let temp = mnemonicTemp[random];
            mnemonicTemp[random] = mnemonicTemp[i];
            mnemonicTemp[i] = temp;
        }
        setRandomMnemonic(mnemonicTemp)
    }
    //更新添加单词
    const updateAddMnemonic = (word:string) => {
        if(!canAddIndex)
        {
            return;
        }

        let addMnemonicTemp = [...addMnemonic];
        addMnemonicTemp[addIndex] = word;
        setAddIndex(addIndex+1);
        setAddMnemonic(addMnemonicTemp)
        console.log(mnemonic)
        console.log(addMnemonicTemp[addIndex],mnemonic[addIndex],addMnemonicTemp[addIndex] !== mnemonic[addIndex])
        if(addMnemonicTemp[addIndex] !== mnemonic[addIndex])
        {
            setCanAddIndex(false)
        }
    }
    //添加错误移除单词
    const removeAddMnemonic = () => {
        console.log(canAddIndex,addIndex)
        if(canAddIndex)
        {
            return;
        }
        let addMnemonicTemp = [...addMnemonic];
        setCanAddIndex(true)
        setAddIndex(addIndex-1);
        addMnemonicTemp[addIndex-1] = " ";
        setAddMnemonic(addMnemonicTemp)

    }
    //确认检查
    const checkMnemonic = async () => {
        if (addMnemonic[addMnemonic.length - 1] === mnemonic[mnemonic.length - 1] && addMnemonic.indexOf(' ') === -1) {
            let wallet = getWalletByMnemonic(mnemonic.join(" "));
            let walletInfoTemp = await getWalletInfo(chainID, wallet.address)
            if (walletInfoTemp) {
                navigation.navigate("L2_Tabs")
                return;
            }
            console.log(wallet.privateKey);
            let walletInfoNow: walletInfoType = {
                address: wallet.address,
                privateKey: wallet.privateKey,
                tip: walletInfo.tip,
                walletName: walletInfo.walletName,
                password: walletInfo.password,
                chainID,
                mnemonic: mnemonic.join(" "),
                balance: "0",
            };
            let addWalletRes = await addWallet(walletInfoNow)
            if (addWalletRes.success) {
                let nowWallet: useWalletType = {chainID, providerUrl: walletInfo.providerUrl, address: wallet.address};
                if (await updateNowWallet(nowWallet)) {
                    navigation.navigate("L2_Tabs");
                    return;
                }
                console.log('Error:updateNowWallet Error')
                return;
            }
            SimpleToast.show(addWalletRes.falseReason);
            if (addWalletRes.falseReason === "地址已添加") {
                navigation.navigate("L2_Tabs");
                return;
            }
            return;
        }
    }
    return (
        <View style={styles.container}>
            <Text style={styles.TipText}>请根据您备份的助记词，按顺序选择填充</Text>
            <View style={styles.mnemonicContainer}>
                {
                    addMnemonic.length?
                        addMnemonic.map((item:string,index:number) => (
                            <TouchableHighlight
                                style={index>=mnemonic.length-3?styles.mnemonicListItemLast:styles.mnemonicListItem}
                                underlayColor={"white"}
                                key={`addMnemonic_${index}`}
                                onPress={()=>{
                                    removeAddMnemonic()
                                }}
                            >
                                <View style={{width:"100%",alignItems:"center",justifyContent:"center"}}>
                                    <Text style={styles.mnemonicListItemContent}>{item}</Text>
                                    {
                                        ((!canAddIndex) && (index === (addIndex - 1))) ?
                                            <View style={{position: "absolute", right: -7, top: -7,backgroundColor:"red",borderRadius:7}}>
                                                <SvgXml xml={closeSvgXml("white")} width={14} height={14}/>
                                            </View>
                                            : null
                                    }
                                </View>
                            </TouchableHighlight>
                        )):null
                }
            </View>
            <View style={styles.mnemonicAddContainer}>
                {
                    randomMnemonic.length?
                        randomMnemonic.map((item:string,index:number) => (
                            <TouchableHighlight
                                underlayColor={"transparent"}
                                key={`mnemonic_${index}`}
                                style={
                                    addMnemonic.indexOf(item) === -1
                                        ?
                                        (index>=mnemonic.length-4?styles.mnemonicAddListItemLast:styles.mnemonicAddListItem)
                                        :
                                        (index>=mnemonic.length-4?styles.mnemonicAddListItemLast_selected:styles.mnemonicAddListItem_selected)
                                }
                                onPress={()=>{
                                    if(addMnemonic.indexOf(item) !== -1)
                                    {
                                        return
                                    }
                                    updateAddMnemonic(item)
                                }}
                            >
                                <Text style={styles.mnemonicListAddItemContent}>{item}</Text>
                            </TouchableHighlight>
                        )):null
                }
            </View>
            <View style={{flex:1}}/>
            <TouchableHighlight
                underlayColor={"#1f83fd"}
                onPress={async () => {
                    console.log(randomMnemonic)
                    console.log(mnemonic)
                    setTimeout(()=>checkMnemonic(),0)
                }}
                style={styles.AllLineBTN}
            >
                <Text style={styles.AllLineBTNTitle}>确认</Text>

            </TouchableHighlight>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 20,
        paddingRight: 20,
        backgroundColor: "white"
    },
    TipText:{
        width:"100%",
        fontSize:fontSize_15,
        color:"black",
        flexWrap:"wrap",
        // paddingLeft:15,
        // fontWeight:"bold",
        // backgroundColor:"pink",
        marginTop:20,
        lineHeight:18,
        letterSpacing:0.5
    },
    mnemonicContainer:{
        width:"100%",
        padding:15,
        marginTop:20,
        marginBottom:20,
        backgroundColor:"#f5f6f8",
        borderRadius:10,
        flexWrap:"wrap",
        flexDirection:"row",
        justifyContent:"space-between",
    },
    mnemonicListItem:{
        width:"29%",
        backgroundColor:"white",
        alignItems:"center",
        justifyContent:"center",
        marginBottom:10
    },
    mnemonicListItemLast:{
        width:"29%",
        backgroundColor:"white",
        alignItems:"center",
        justifyContent:"center",
    },
    mnemonicListItemContent:{
        fontSize: fontSize_15,
        lineHeight:40,
    },
    mnemonicListItemFalseContent:{
        fontSize: fontSize_15,
        lineHeight:40,
        color:"red"
    },
    mnemonicAddContainer:{
        width:"100%",
        padding:0,
        marginTop:10,
        marginBottom:20,
        backgroundColor:"white",
        borderRadius:0,
        flexWrap:"wrap",
        flexDirection:"row",
        justifyContent:"space-between",
    },
    mnemonicAddListItem:{
        width:"22%",
        backgroundColor:"white",
        alignItems:"center",
        justifyContent:"center",
        marginBottom:10,
        borderWidth:2/scale,
        borderRadius:5
    },
    mnemonicAddListItemLast:{
        width:"22%",
        backgroundColor:"white",
        alignItems:"center",
        justifyContent:"center",
        borderWidth:2/scale,
        borderRadius:5
    },
    mnemonicAddListItem_selected:{
        width:"22%",
        backgroundColor:"#f5f6f8",
        alignItems:"center",
        justifyContent:"center",
        marginBottom:10,
        borderWidth:2/scale,
        borderRadius:5
    },
    mnemonicAddListItemLast_selected:{
        width:"22%",
        backgroundColor:"#f5f6f8",
        alignItems:"center",
        justifyContent:"center",
        borderWidth:2/scale,
        borderRadius:5
    },
    mnemonicListAddItemContent:{
        fontSize: fontSize_12,
        lineHeight:35,
    },
    AllLineBTN:{
        width:"100%",
        height:40,
        backgroundColor:"#1f83fd",
        justifyContent:"center",
        alignItems:"center",
        borderRadius:5,
        marginTop:10,
        marginBottom:10,
    },
    AllLineBTNTitle:{
        fontSize:fontSize_16,
        color:"white",
    },
})
export default L2_CheckMnemonicView;


